/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Conexao;

import Opcoes.Conexoes;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author William
 */
public class Download implements Runnable{

    private int file_index;
    private String file_name;

    public Download (int file_index,String file_name)
    {
        this.file_index = file_index;
        this.file_name = file_name;
    }

    public void run() {
        try {

            StringTokenizer token;
            Socket socket = new Socket("localhost", Conexoes.CONNECT_PORT);
            String msg;
            int fileSize = 0;

            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());

            msg = "GET /get/" + file_index + "/" + file_name + "/ HTTP/1.0\r\n";
            msg += "Connection: Keep-Alive\r\n";
            msg += "Range: bytes=0-\r\n";
            msg += "User-Agent: Gnutella\r\n" + "\r\n";

            //msg = "GIV " + file_index + ":1234567890123456/" + file_name + "\n\n";

            out.writeUTF(msg);

            msg = in.readUTF();

            System.out.printf("%s",msg);
            
            token = new StringTokenizer(msg,":");

            token.nextToken("\r");
            token.nextToken("\r");
            token.nextToken("\r");
            token.nextToken(" ");
            fileSize = Integer.parseInt(token.nextToken("\r").trim());

            File fileDownloaded = new File("Downloads/DOWN " + file_name);
            FileOutputStream fileOut = new FileOutputStream(fileDownloaded);

            System.out.println("Nome: " + file_name + "   Size: " + fileSize);

            byte[] fileBuffer = new byte[fileSize];

            
            in.readFully(fileBuffer);
            fileOut.write(fileBuffer);

            socket.close();

        } catch (UnknownHostException ex) {
            Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
        }
    }



}
